<script setup lang="ts">
import * as THREE from 'three'
import { ref, onMounted } from 'vue'

const domEl = ref(null)

const initTexture = (domEl) => {
  const canvas = domEl
  const renderer = new THREE.WebGLRenderer({antialias: true, canvas})

  const camera = new THREE.PerspectiveCamera(75, domEl.clientWidth / domEl.clientHeight, 0.1, 1000)
  camera.position.z = 5

  const scene = new THREE.Scene()

  // 纹理
  const loader = new THREE.TextureLoader()
  const loadColorTexture = ( path ) => {
    const texture = loader.load( path )
    texture.colorSpace = THREE.SRGBColorSpace
    return texture
  }
  const materials = [
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/css.jpg')}),
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/html.jpg')}),
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/css2.jpg')}),
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/web.jpg')}),
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/javascript.jpg')}),
    new THREE.MeshPhongMaterial({map: loadColorTexture('/zm-docs/imgs/javascript1.jpg')}),
  ]

  const geometry = new THREE.BoxGeometry( 1, 1, 1 )

  const cube = new THREE.Mesh( geometry, materials )
  scene.add( cube )

  {
    const color = 0xFFFFFF
    const intensity = 3
    const light = new THREE.DirectionalLight(color, intensity)
    light.position.set(-1, 2, 4)
    scene.add(light)
  }

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement
    const pixelRatio = window.devicePixelRatio
    const width = canvas.clientWidth * pixelRatio | 0
    const height = canvas.clientHeight * pixelRatio | 0
    const needResize = canvas.width !== width || canvas.height !== height
    if (needResize) {
      renderer.setSize(width, height, false)
    }
    return needResize
  }

  function render(time) {
    time *= 0.001

    if ( resizeRendererToDisplaySize( renderer ) ) {

      const canvas = renderer.domElement
      camera.aspect = canvas.clientWidth / canvas.clientHeight
      camera.updateProjectionMatrix()

    }

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
    renderer.render(scene, camera)

    requestAnimationFrame(render)
  }

  requestAnimationFrame(render)

}

onMounted(() => {
  initTexture(domEl.value)
})

</script>

<template>
  <canvas ref="domEl" class="w-full h-full"></canvas>
</template>

<style scoped lang="scss">

</style>